package com.yfq.springframework.beans.support;

import com.yfq.springframework.beans.DisposableBean;
import com.yfq.springframework.beans.config.BeanDefinition;
import com.yfq.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * @author 姚凤桥
 * @date 2023/1/30 21:14
 * @description 对象销毁方法适配器
 */
public class DisposableBeanAdapter implements DisposableBean {
    private final String beanName;

    private final Object bean;

    private final String destroyMethodName;

    public DisposableBeanAdapter(String beanName, Object bean, BeanDefinition beanDefinition) {
        this.beanName = beanName;
        this.bean = bean;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {
        if (bean instanceof DisposableBean) {
            DisposableBean disposableBean = (DisposableBean) bean;
            disposableBean.destroy();
        }

        //这里判断是为了避免destroy被执行两次
        if (!StringUtils.isEmpty(destroyMethodName)
                && !(bean instanceof DisposableBean && "destroy".equals(destroyMethodName))) {
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);

            destroyMethod.invoke(bean);
        }
    }

}
